package org.jeecg.modules.wmhb.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wmhb.vo.*;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.modules.wmhb.util.WmhbUtil;

/**
 * @Description: 项目表
 * @Author: jeecg-boot
 * @Date: 2024-09-02
 * @Version: V1.0
 */
@Api(tags = "项目表")
@RestController
@RequestMapping("/wmhb/wmProject")
@Slf4j
public class WmProjectController extends JeecgController<WmProject, IWmProjectService> {
    @Autowired
    private IWmProjectService wmProjectService;
    @Autowired
    private IWmContractService wmContractService;
    @Autowired
    private IWmContractProductService wmContractProductService;
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IWmProjectStatisticService wmProjectStatisticService;
    @Autowired
    private IWmTaskBomService wmTaskBomService;
    @Autowired
    private IWmPurchaseTaskbookBomService wmPurchaseTaskbookBomService;
    @Autowired
    private IWmItemService wmItemService;
    @Autowired
    private IWmVendorService wmVendorService;
    @Autowired
    private IWmTaskbookService wmTaskbookService;
    @Autowired
    ISysBaseAPI sysBaseApi;

    /**
     * 分页列表查询
     *
     * @param wmProject
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "项目表-分页列表查询")
    @ApiOperation(value = "项目表-分页列表查询", notes = "项目表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmProject>> queryPageList(WmProject wmProject,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        QueryWrapper<WmProject> queryWrapper = QueryGenerator.initQueryWrapper(wmProject, req.getParameterMap());
        Page<WmProject> page = new Page<WmProject>(pageNo, pageSize);
        queryWrapper.orderByDesc("create_time");
        IPage<WmProject> pageList = wmProjectService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmProject
     * @return
     */
    @AutoLog(value = "项目表-添加")
    @ApiOperation(value = "项目表-添加", notes = "项目表-添加")
    @RequiresPermissions("wmhb:wm_project:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WmProject wmProject) {
        if (UserConstant.NOT_UNIQUE.equals(wmProjectService.checkCodeUnique(wmProject))) {
            return Result.error("新增项目失败，项目编码已存在");
        }
        if (UserConstant.NOT_UNIQUE.equals(wmProjectService.checkNameUnique(wmProject))) {
            return Result.error("新增项目失败，项目名称已存在");
        }

        if (StringUtils.isEmpty(wmProject.getCode())) {
            String code = (String) FillRuleUtil.executeRule(FillRuleConstant.PROJECT, null);
            wmProject.setCode(code);
        }

        wmProjectService.save(wmProject);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmProject
     * @return
     */
    @AutoLog(value = "项目表-编辑")
    @ApiOperation(value = "项目表-编辑", notes = "项目表-编辑")
    @RequiresPermissions("wmhb:wm_project:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmProject wmProject) {
        if (UserConstant.NOT_UNIQUE.equals(wmProjectService.checkCodeUnique(wmProject))) {
            return Result.error("编辑项目" + wmProject.getCode() + "失败，项目编码已存在");
        }
        if (UserConstant.NOT_UNIQUE.equals(wmProjectService.checkNameUnique(wmProject))) {
            return Result.error("编辑项目" + wmProject.getCode() + "失败，项目名称已存在");
        }

        wmProjectService.updateById(wmProject);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目表-通过id删除")
    @ApiOperation(value = "项目表-通过id删除", notes = "项目表-通过id删除")
    @RequiresPermissions("wmhb:wm_project:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        if (wmProjectService.checkHasItem(id)) {
            return Result.error("项目下有合同，请先删除合同");
        }
        wmProjectService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目表-批量删除")
    @ApiOperation(value = "项目表-批量删除", notes = "项目表-批量删除")
    @RequiresPermissions("wmhb:wm_project:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> oldIdList = Arrays.asList(ids.split(","));
        List<String> newIdList = new ArrayList<>();
        List<String> filterIdList = new ArrayList<>();
        for (String id : oldIdList) {
            if (!wmProjectService.checkHasItem(id)) {
                newIdList.add(id);
            } else {
                filterIdList.add(id);
            }
        }

        String filterStr = String.join(",", filterIdList);
        if (!CollectionUtils.isEmpty(newIdList)) {
            this.wmProjectService.removeByIds(newIdList);
            if (CollectionUtils.isEmpty(filterIdList)) {
                return Result.OK("批量删除成功！");
            } else {
                String newStr = String.join(",", newIdList);
                return Result.OK("ID为" + newStr + "批量删除成功，ID为" + filterStr + "的删除失败，原因：项目下有合同！");
            }
        } else {
            return Result.error("批量删除失败，原因：项目下有合同！");
        }
    }

    /**
     * 通过id查询
     *
     * @param currentProjectId
     * @return
     */
    //@AutoLog(value = "项目表-通过id查询")
    @ApiOperation(value = "项目表-通过id查询", notes = "项目表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmProject> queryById(@RequestParam(name = "currentProjectId", required = true) String currentProjectId) {
        WmProject wmProject = wmProjectService.getById(currentProjectId);
        if (wmProject == null) {
            return Result.error("未找到对应数据");
        }

        //项目所有合同（非草稿状态）
        List<String> wmContractIdList = new ArrayList<>();
        List<WmContract> wmContractList = wmContractService.queryGantContractByWmProjectId(wmProject.getId());
        for(WmContract wmContract: wmContractList){
            if(!wmContract.getStatus().equals(UserConstant.CONTRACT_STATUS_PREPARE)) {
                wmContractIdList.add(wmContract.getId());
            }
        }

        //统计数据初始化
        WmProjectStatisticVo wmProjectStatisticVo = new WmProjectStatisticVo();
        wmProjectStatisticVo.setNotStartTaskNum(0);
        wmProjectStatisticVo.setDoingTaskNum(0);
        wmProjectStatisticVo.setCompletedTaskNum(0);

        //所有合同产品
        if(!wmContractIdList.isEmpty()) {
            List<String> wmContractProductList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
            if (!wmContractProductList.isEmpty()) {
                //根任务排行列表
                List<WmTask> wmTaskList = wmTaskService.selectRemainTaskRankByContractProduct(wmContractProductList);

                //任务统计数量
                List<WmProjectStatistic> wmProjectStatisticList = wmProjectStatisticService.getByProject(currentProjectId);
                wmProjectStatisticVo = wmTaskService.getStatisticByContractProduct(wmContractProductList);
                wmProjectStatisticVo.setProjectStatisticList(wmProjectStatisticList);
                wmProjectStatisticVo.setBurningNumList(getBurningGraph(wmProject));
                wmProjectStatisticVo.setTaskList(wmTaskList);
            }
        }
        wmProject.setProjectStatisticVo(wmProjectStatisticVo);

        return Result.OK(wmProject);
    }

    /**
     * 项目燃尽图
     * @param wmProject
     * @return
     */
    private List<BurningGraph> getBurningGraph(WmProject wmProject){
        List<WmContract> wmContractList = wmContractService.listByProject(wmProject);
        List<WmContractProduct> wmContractProductList = wmContractProductService.listByContractList(wmContractList);
        List<WmTask> wmTaskList = wmTaskService.listByContractProductList(wmContractProductList);
        List<BurningGraph> burningGraphList = new ArrayList<>();
        BurningGraph burningGraphStart = new BurningGraph();
        burningGraphStart.setDate(wmProject.getPlanBeginTime());
        Integer startNum = wmTaskList.size();
        burningGraphStart.setNum(startNum);
        burningGraphList.add(burningGraphStart);
        BurningGraph burningGraphEnd = new BurningGraph();
        burningGraphEnd.setDate(wmProject.getPlanEndTime());
        burningGraphEnd.setNum(0);
        burningGraphList.add(burningGraphEnd);

        return burningGraphList;
    };

    /**
     * 导出excel
     *
     * @param request
     * @param wmProject
     */
    @RequiresPermissions("wmhb:wm_project:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmProject wmProject) {
        return super.exportXls(request, wmProject, WmProject.class, "项目表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("wmhb:wm_project:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WmProject.class);
    }

    /**
     * 确认
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目表-确认")
    @ApiOperation(value = "项目表-确认", notes = "项目表-确认")
    @RequiresPermissions("wmhb:wm_project:confirm")
    @Transactional
    @RequestMapping(value = "/confirm", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> doConfirm(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for(String id: idList) {
            WmProject wmProject = wmProjectService.getById(id);
            if(!wmProject.getStatus().equals(UserConstant.PROJECT_STATUS_PREPARE)){{
                throw new RuntimeException("只有草稿状态能确认");
            }}

            //wmProject.setProgress("10");
            wmProject.setStatus(UserConstant.PROJECT_STATUS_CONFIRMED); //更新项目的状态
            wmProjectService.updateById(wmProject);
        }
        return Result.OK("操作成功");
    }

    /**
     * 完成
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目表-完成")
    @ApiOperation(value = "项目表-完成", notes = "项目表-完成")
    @RequiresPermissions("wmhb:wm_project:finish")
    @Transactional
    @RequestMapping(value = "/finish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> doFinish(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for(String id: idList) {
            WmProject wmProject = wmProjectService.getById(id);
            if(!wmProject.getStatus().equals(UserConstant.PROJECT_STATUS_CONFIRMED)){{
                throw new RuntimeException("只有确认状态能确认");
            }}

            wmProject.setProgress("100");
            wmProject.setStatus(UserConstant.PROJECT_STATUS_FINISHED); //更新项目的状态
            wmProjectService.updateById(wmProject);
        }
        return Result.OK("操作成功");
    }

    /**
     * 通过id查询甘特图数据
     *
     * @param currentProjectId
     * @return
     */
    //@AutoLog(value = "项目表-通过id查询甘特图数据")
    @ApiOperation(value = "项目表-通过id查询甘特图数据", notes = "项目表-通过id查询甘特图数据")
    @GetMapping(value = "/queryGantById")
    public Result<List<WmProjectGantVo>> queryGantById(@RequestParam(name = "currentProjectId", required = true) String currentProjectId) {
        List<WmProjectGantVo> wmProjectGantVoList = new ArrayList<>();
        WmProject wmProject = wmProjectService.getById(currentProjectId);
        if (wmProject == null) {
            return Result.error("未找到对应数据");
        }
        WmProjectGantVo wmProjectGantVoOfProject =  new WmProjectGantVo();
        wmProjectGantVoOfProject.setId(wmProject.getId());
        wmProjectGantVoOfProject.setText(wmProject.getName());
        wmProjectGantVoOfProject.setStart_date(wmProject.getPlanBeginTime());
        wmProjectGantVoOfProject.setEnd_date(wmProject.getPlanEndTime());
        Double progressOfProject = (Double.parseDouble(wmProject.getProgress())/100); ;
        wmProjectGantVoOfProject.setProgress(progressOfProject);
        wmProjectGantVoOfProject.setType(UserConstant.GANT_TYPE_PROJECT);
        wmProjectGantVoOfProject.setTypeName("项目");
        String projectStatus = sysDictService.queryDictTextByKey(UserConstant.PROJECT_STATUS, wmProject.getStatus());
        wmProjectGantVoOfProject.setStatus(projectStatus);
        wmProjectGantVoList.add(wmProjectGantVoOfProject);

        List<WmContract> wmContractList = wmContractService.queryGantContractByWmProjectId(wmProject.getId());
        for(WmContract wmContract: wmContractList){
            WmProjectGantVo wmProjectGantVoOfContract =  new WmProjectGantVo();
            wmProjectGantVoOfContract.setId(wmContract.getId());
            wmProjectGantVoOfContract.setParent(wmProject.getId());
            wmProjectGantVoOfContract.setText(wmContract.getName());
            wmProjectGantVoOfContract.setStart_date(wmContract.getPlanBeginTime());
            wmProjectGantVoOfContract.setEnd_date(wmContract.getPlanEndTime());
            Double progressOfContract = (Double.parseDouble(wmContract.getProgress())/100); ;
            wmProjectGantVoOfContract.setProgress(progressOfContract);
            wmProjectGantVoOfContract.setType(UserConstant.GANT_TYPE_CONTRACT);
            wmProjectGantVoOfContract.setTypeName("合同");
            String contractStatus = sysDictService.queryDictTextByKey(UserConstant.CONTRACT_STATUS, wmContract.getStatus());
            wmProjectGantVoOfContract.setStatus(contractStatus);
            wmProjectGantVoList.add(wmProjectGantVoOfContract);

            List<String> wmContractIdList = new ArrayList<>();
            wmContractIdList.add(wmContract.getId());
            List<String> wmContractProductList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
            if(!wmContractProductList.isEmpty()) {
                List<WmTask> statisticTaskList = wmTaskService.selectStatisticTaskByContractProduct(wmContractProductList);//非生产任务书任务（所有根任务）,生产任务书任务(所有设计起点任务)
                List<WmTask> ancestorTaskList = wmTaskService.selectAncestorTaskList(statisticTaskList);//祖先任务
                List<WmTask> wmTaskList = new ArrayList<>();
                wmTaskList.addAll(ancestorTaskList);
                for (WmTask wmTask1 : statisticTaskList) {
                    Boolean flag = false;
                    for (WmTask wmTask2 : ancestorTaskList) {
                        if (wmTask1.getId().equals(wmTask2.getId())) {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        wmTaskList.add(wmTask1);
                    }
                }

                for (WmTask wmTask : wmTaskList) {
                    WmProjectGantVo wmProjectGantVoOfTask = new WmProjectGantVo();
                    wmProjectGantVoOfTask.setId(wmTask.getId());
                    if (wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
                        wmProjectGantVoOfTask.setParent(wmContract.getId());
                    } else {
                        wmProjectGantVoOfTask.setParent(wmTask.getPid());
                    }
                    wmProjectGantVoOfTask.setText(wmTask.getName());
                    wmProjectGantVoOfTask.setStart_date(wmTask.getPlanBeginTime());
                    wmProjectGantVoOfTask.setEnd_date(wmTask.getPlanEndTime());
                    Double progressOfTask = (Double.parseDouble(wmTask.getProgress()) / 100);
                    ;
                    wmProjectGantVoOfTask.setProgress(progressOfTask);
                    //生产任务书类型
                    List<String> produceTypeList = new ArrayList<>();
                    produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE);
                    produceTypeList.add(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC);
                    if (produceTypeList.contains(wmTask.getTaskbookType())) {
                        wmProjectGantVoOfTask.setType(UserConstant.GANT_TYPE_PRODUCE_TASK);
                        wmProjectGantVoOfTask.setTypeName("生产任务");
                    } else if (wmTask.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN)) {
                        wmProjectGantVoOfTask.setType(UserConstant.GANT_TYPE_DESIGN_TASK);
                        wmProjectGantVoOfTask.setTypeName("设计任务");
                    } else if (wmTask.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DEBUG)) {
                        wmProjectGantVoOfTask.setType(UserConstant.GANT_TYPE_DEBUG_TASK);
                        wmProjectGantVoOfTask.setTypeName("安装调试任务");
                    } else if (wmTask.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_TECHNOLOGY)) {
                        wmProjectGantVoOfTask.setType(UserConstant.GANT_TYPE_TECHNOLOGY_TASK);
                        wmProjectGantVoOfTask.setTypeName("技术服务任务");
                    } else if (wmTask.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PURCHASE)) {
                        wmProjectGantVoOfTask.setType(UserConstant.GANT_TYPE_PURCHASE_TASK);
                        wmProjectGantVoOfTask.setTypeName("采购任务");
                    } else if (wmTask.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PROCESS)) {
                        wmProjectGantVoOfTask.setType(UserConstant.GANT_TYPE_PURCHASE_TASK);
                        wmProjectGantVoOfTask.setTypeName("工艺任务");
                    }

                    String taskStatus = sysDictService.queryDictTextByKey(UserConstant.TASK_STATUS, wmTask.getStatus());
                    wmProjectGantVoOfTask.setStatus(taskStatus);
                    wmProjectGantVoList.add(wmProjectGantVoOfTask);
                }
            }
        }

        return Result.OK(wmProjectGantVoList);
    }

    /**
     * 编辑甘特图
     *
     * @param wmProjectGantVo
     * @return
     */
    @AutoLog(value = "项目表-编辑甘特图")
    @ApiOperation(value = "项目表-编辑甘特图", notes = "项目表-编辑甘特图")
    @RequiresPermissions("wmhb:wm_project:updateGant")
    @RequestMapping(value = "/updateGant", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> updateGant(@RequestBody WmProjectGantVo wmProjectGantVo) {
        List<String> taskTypeList = new ArrayList<>();
        taskTypeList.add(UserConstant.GANT_TYPE_PRODUCE_TASK);
        taskTypeList.add(UserConstant.GANT_TYPE_DESIGN_TASK);
        taskTypeList.add(UserConstant.GANT_TYPE_DEBUG_TASK);
        taskTypeList.add(UserConstant.GANT_TYPE_TECHNOLOGY_TASK);
        taskTypeList.add(UserConstant.GANT_TYPE_PURCHASE_TASK);

        if(wmProjectGantVo.getType().equals(UserConstant.GANT_TYPE_PROJECT)){
            WmProject wmProject = wmProjectService.getById(wmProjectGantVo.getId());
            wmProject.setPlanBeginTime(wmProjectGantVo.getStart_date());
            wmProject.setPlanEndTime(wmProjectGantVo.getEnd_date());
            wmProjectService.updateById(wmProject);
        }
        else if(wmProjectGantVo.getType().equals(UserConstant.GANT_TYPE_CONTRACT)){
            WmContract wmContract = wmContractService.getById(wmProjectGantVo.getId());
            wmContract.setPlanBeginTime(wmProjectGantVo.getStart_date());
            wmContract.setPlanEndTime(wmProjectGantVo.getEnd_date());
            wmContractService.updateById(wmContract);
        }
        else if(taskTypeList.contains(wmProjectGantVo.getType())){
            WmTask wmTask = wmTaskService.getById(wmProjectGantVo.getId());
            wmTask.setPlanBeginTime(wmProjectGantVo.getStart_date());
            wmTask.setPlanEndTime(wmProjectGantVo.getEnd_date());
            wmTaskService.updateById(wmTask);
        }

        return Result.OK("操作成功!");
    }

    /**
     * 通过id查询发货清单数据(本月)
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "项目表-通过id查询发货清单数据(本月)")
    @ApiOperation(value = "项目表-通过id查询发货清单数据(本月)", notes = "项目表-通过id查询发货清单数据(本月)")
    @GetMapping(value = "/sendList")
    public Result<List<WmProjectSendListVo>> sendList(@RequestParam(name = "id", required = true) String id){
        WmProject wmProject = wmProjectService.getById(id);
        if (wmProject == null) {
            return Result.error("未找到对应数据");
        }

        String firstDayOfMonth = WmhbUtil.getFirstDayOfMonth(new Date());
        String lastDayOfMonth = WmhbUtil.getLastDayOfMonth(new Date());
        List<WmProjectSendListVo> wmProjectSendListVoList = new ArrayList<>();
        List<WmContract> wmContractList = wmContractService.queryGantContractByWmProjectId(id);
        for(WmContract wmContract: wmContractList){
            List<String> wmContractIdList = new ArrayList<>();
            wmContractIdList.add(wmContract.getId());
            List<String> wmContractProductList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
            if(!wmContractProductList.isEmpty()){
                //1、生产任务BOM
                List<WmTask> sendUnitTaskList = wmTaskService.selectSendUnitTask(wmContractProductList, firstDayOfMonth, lastDayOfMonth);
                for (WmTask wmTaskItem : sendUnitTaskList) {
                    WmProjectSendListVo wmProjectSendListVo = new WmProjectSendListVo();
                    wmProjectSendListVo.setProjectName(wmProject.getName());
                    wmProjectSendListVo.setQuantity(wmTaskItem.getQuantity());
                    wmProjectSendListVo.setSpecification(wmTaskItem.getSpecification());
                    wmProjectSendListVo.setProductName(wmTaskItem.getName());
                    wmProjectSendListVo.setProductCode(wmTaskItem.getCode());
                    String isOver = wmTaskItem.getStatus().equals(UserConstant.TASK_STATUS_FINISHED) ? "是" : "否";
                    wmProjectSendListVo.setIsOver(isOver);
                    SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTaskItem.getBuId());
                    wmProjectSendListVo.setBuName(sysDepartModel.getDepartName());
                    if(!StringUtils.isEmpty(wmTaskItem.getUnitOfMeasure())) {
                        String dictText = sysDictService.queryDictTextByKey(UserConstant.UNIT_OF_MESSURE, wmTaskItem.getUnitOfMeasure());
                        wmProjectSendListVo.setUnitOfMeasure(dictText);
                    }
                    wmProjectSendListVo.setWmContractId(wmContract.getId());
                    if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_SELF)){
                        wmProjectSendListVo.setWarehouseName(sysDepartModel.getProductWarehouseId());
                    }
                    else if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_BUY)) {
                        wmProjectSendListVo.setWarehouseName(sysDepartModel.getVendorWarehouseId());
                    }
                    else if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_OUT)) {
                        wmProjectSendListVo.setWarehouseName(sysDepartModel.getOutSourceWarehouseId());
                    }
                    WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
                    wmProjectSendListVo.setWmTaskbookId(wmTaskbook.getCode());
                    wmProjectSendListVoList.add(wmProjectSendListVo);
                }

                //2、采购任务BOM
                List<WmTask> purchaseTaskList = wmTaskService.selectPurchaseTask(wmContractProductList);
                for (WmTask wmTaskItem : purchaseTaskList) {
                    List<WmPurchaseTaskbookBom> wmPurchaseTaskbookBomList = wmPurchaseTaskbookBomService.listByWmTaskIdAndStartEnd(wmTaskItem.getId(), firstDayOfMonth, lastDayOfMonth);
                    for(WmPurchaseTaskbookBom wmPurchaseTaskbookBom: wmPurchaseTaskbookBomList){
                        WmProjectSendListVo wmProjectSendListVo = new WmProjectSendListVo();
                        wmProjectSendListVo.setProjectName(wmProject.getName());
                        wmProjectSendListVo.setQuantity(wmPurchaseTaskbookBom.getQuantity());
                        wmProjectSendListVo.setSpecification(wmPurchaseTaskbookBom.getSpecification());
                        wmProjectSendListVo.setProductName(wmPurchaseTaskbookBom.getName());
                        wmProjectSendListVo.setProductCode(wmPurchaseTaskbookBom.getCode());
                        String isOver = wmTaskItem.getStatus().equals(UserConstant.TASK_STATUS_FINISHED) ? "是" : "否";
                        wmProjectSendListVo.setIsOver(isOver);
                        SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTaskItem.getBuId());
                        wmProjectSendListVo.setBuName(sysDepartModel.getDepartName());
                        if(!StringUtils.isEmpty(wmTaskItem.getUnitOfMeasure())) {
                            String dictText = sysDictService.queryDictTextByKey(UserConstant.UNIT_OF_MESSURE, wmPurchaseTaskbookBom.getUnitOfMeasure());
                            wmProjectSendListVo.setUnitOfMeasure(dictText);
                        }
                        wmProjectSendListVo.setWmContractId(wmContract.getId());
                        if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_SELF)){
                            wmProjectSendListVo.setWarehouseName(sysDepartModel.getProductWarehouseId());
                        }
                        else if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_BUY)) {
                            wmProjectSendListVo.setWarehouseName(sysDepartModel.getVendorWarehouseId());
                        }
                        else if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_OUT)) {
                            wmProjectSendListVo.setWarehouseName(sysDepartModel.getOutSourceWarehouseId());
                        }

                        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTaskItem.getWmTaskbookId());
                        wmProjectSendListVo.setWmTaskbookId(wmTaskbook.getCode());
                        wmProjectSendListVoList.add(wmProjectSendListVo);
                    }
                }
            }
        }

        return Result.OK(wmProjectSendListVoList);
    }

    /**
     * 查询生产部/事业部生产明细
     *
     * @param buId
     * @param yearMonth
     * @return
     */
    //@AutoLog(value = "查询生产部/事业部生产明细")
    @ApiOperation(value = "项目表-查询生产部/事业部生产明细", notes = "项目表-查询生产部/事业部生产明细")
    @GetMapping(value = "/produceDetail")
    public Result<List<WmProduceDetailVo>> produceDetail(@RequestParam(name = "buId", required = false) String buId, @RequestParam(name = "yearMonth", required = false) String yearMonth){
        String firstDayOfMonth = WmhbUtil.getFirstDayOfMonth(new Date());
        String lastDayOfMonth = WmhbUtil.getLastDayOfMonth(new Date());
        if(!StringUtils.isEmpty(yearMonth)){
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
            try {
                Date date = formatter.parse(yearMonth); // 解析字符串为Date对象
                firstDayOfMonth = WmhbUtil.getFirstDayOfMonth(date);
                lastDayOfMonth = WmhbUtil.getLastDayOfMonth(date);
            } catch (ParseException e) {
                return Result.error(e.getMessage()); // 处理异常
            }
        }

        List<WmProduceDetailVo> wmProduceDetailVoList = new ArrayList<>();
        List<String> wmContractIdList = new ArrayList<>();
        List<WmProject> wmProjectList = wmProjectService.list();
        for(WmProject wmProject: wmProjectList){
            List<WmContract> wmContractList = wmContractService.queryGantContractByWmProjectId(wmProject.getId());
            for(WmContract wmContract: wmContractList) {
                wmContractIdList.add(wmContract.getId());
            }
        }

        if (!wmContractIdList.isEmpty()) {
            List<String> wmContractProductList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
            if (!wmContractProductList.isEmpty()) {
                List<WmProductRecpt> wmProductRecptList = wmTaskService.selectStartPointTask(wmContractProductList, firstDayOfMonth, lastDayOfMonth);
                for (WmProductRecpt wmProductRecpt : wmProductRecptList) {
                    WmTask wmTask = wmTaskService.getById(wmProductRecpt.getWmTaskId());
                    if (!StringUtils.isEmpty(buId) && !wmTask.getBuId().equals(buId)) {
                        continue;
                    }
                    SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getBuId());
                    WmProduceDetailVo wmProduceDetailVo = new WmProduceDetailVo();
                    wmProduceDetailVo.setProducingQuantity(String.valueOf(wmProductRecpt.getRemainQuantity()));
                    wmProduceDetailVo.setCompleteQuantity(String.valueOf(wmTask.getCompleteNum()));
                    wmProduceDetailVo.setProducingMeterialRate(wmProductRecpt.getBomRecptPercent());
                    wmProduceDetailVo.setProducingCompleteRate(wmProductRecpt.getNotCompletePercent());
                    wmProduceDetailVo.setHourPrice("");
                    wmProduceDetailVo.setBuName(sysDepartModel.getDepartName());
                    wmProduceDetailVo.setDesignQuantity(wmTask.getQuantity());
                    wmProduceDetailVo.setProductName(wmTask.getName());
                    wmProduceDetailVo.setProductCode(wmTask.getCode());
                    wmProduceDetailVo.setSpecification(wmTask.getSpecification());
                    if(!StringUtils.isEmpty(wmTask.getUnitOfMeasure())) {
                        String dictText = sysDictService.queryDictTextByKey(UserConstant.UNIT_OF_MESSURE, wmTask.getUnitOfMeasure());
                        wmProduceDetailVo.setUnitOfMeasure(dictText);
                    }

                    WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
                    wmProduceDetailVo.setWmTaskbookId(wmTaskbook.getCode());
                    wmProduceDetailVoList.add(wmProduceDetailVo);
                }
            }
        }
        return Result.OK(wmProduceDetailVoList);
    }

    /**
     * 查询生产部/事业部外协加工费统计
     *
     * @param buId
     * @param yearMonth
     * @return
     */
    //@AutoLog(value = "查询生产部/事业部外协加工费统计")
    @ApiOperation(value = "项目表-查询生产部/事业部外协加工费统计", notes = "项目表-查询生产部/事业部外协加工费统计")
    @GetMapping(value = "/outSourceStatistic")
    public Result<List<WmOutSourceStatisticVo>> outSourceStatistic(@RequestParam(name = "buId", required = false) String buId, @RequestParam(name = "yearMonth", required = false) String yearMonth){
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = WmhbUtil.getFirstDayOfMonth(new Date());
        String lastDayOfMonth = WmhbUtil.getLastDayOfMonth(new Date());
        if(!StringUtils.isEmpty(yearMonth)){
            try {
                Date date = formatter1.parse(yearMonth); // 解析字符串为Date对象
                firstDayOfMonth = WmhbUtil.getFirstDayOfMonth(date);
                lastDayOfMonth = WmhbUtil.getLastDayOfMonth(date);
            } catch (ParseException e) {
                return Result.error(e.getMessage()); // 处理异常
            }
        }
        else{
            yearMonth = formatter1.format(new Date());
        }

        List<WmOutSourceStatisticVo> wmOutSourceStatisticVoList = new ArrayList<>();
        List<String> wmContractIdList = new ArrayList<>();
        List<WmProject> wmProjectList = wmProjectService.list();
        for(WmProject wmProject: wmProjectList){
            List<WmContract> wmContractList = wmContractService.queryGantContractByWmProjectId(wmProject.getId());
            for(WmContract wmContract: wmContractList) {
                wmContractIdList.add(wmContract.getId());
            }
        }

        if (!wmContractIdList.isEmpty()) {
            List<String> wmContractProductList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
            if (!wmContractProductList.isEmpty()) {
                List<WmOutSource> wmOutSourceList = wmTaskService.selectOutSourceTask(wmContractProductList, firstDayOfMonth, lastDayOfMonth);
                for (WmOutSource wmOutSource : wmOutSourceList) {
                    WmTask wmTask = wmTaskService.getById(wmOutSource.getWmTaskId());
                    if (!StringUtils.isEmpty(buId) && !wmTask.getBuId().equals(buId)) {
                        continue;
                    }
                    SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getBuId());

                    WmOutSourceStatisticVo wmOutSourceStatisticVo = new WmOutSourceStatisticVo();
                    if(wmTask.getStatus().equals(UserConstant.TASK_STATUS_FINISHED)){
                        String finishDate = formatter2.format(wmTask.getUpdateTime());
                        wmOutSourceStatisticVo.setCompleteDate(finishDate);
                    }

                    wmOutSourceStatisticVo.setYearMonth(yearMonth);
                    wmOutSourceStatisticVo.setRemark("");
                    if(!StringUtils.isEmpty(wmOutSource.getWmVendorId())) {
                        WmVendor wmVendor = wmVendorService.getById(wmOutSource.getWmVendorId());
                        if(wmVendor != null) {
                            wmOutSourceStatisticVo.setVendorName(wmVendor.getCnName());
                        }
                    }

                    wmOutSourceStatisticVo.setTotalMoney(String.valueOf(wmOutSource.getTotalFee()));
                    wmOutSourceStatisticVo.setPrice(wmOutSource.getFeeStandard());
                    wmOutSourceStatisticVo.setBuName(sysDepartModel.getDepartName());
                    wmOutSourceStatisticVo.setQuantity(wmTask.getQuantity());
                    wmOutSourceStatisticVo.setProductName(wmTask.getName());
                    wmOutSourceStatisticVo.setProductCode(wmTask.getCode());
                    wmOutSourceStatisticVo.setSpecification(wmTask.getSpecification());
                    if(!StringUtils.isEmpty(wmTask.getUnitOfMeasure())) {
                        String dictText = sysDictService.queryDictTextByKey(UserConstant.UNIT_OF_MESSURE, wmTask.getUnitOfMeasure());
                        wmOutSourceStatisticVo.setUnitOfMeasure(dictText);
                    }

                    WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
                    wmOutSourceStatisticVo.setWmTaskbookId(wmTaskbook.getCode());
                    wmOutSourceStatisticVoList.add(wmOutSourceStatisticVo);
                }
            }
        }
        return Result.OK(wmOutSourceStatisticVoList);
    }

    /**
     * 查询生产部/事业部项目安装及其他费用统计
     *
     * @param buId
     * @param yearMonth
     * @return
     */
    //@AutoLog(value = "查询生产部/事业部项目安装及其他费用统计")
    @ApiOperation(value = "项目表-查询生产部/事业部项目安装及其他费用统计", notes = "项目表-查询生产部/事业部项目安装及其他费用统计")
    @GetMapping(value = "/installDebugStatistic")
    public Result<List<WmInstallDebugVo>> installDebugStatistic(@RequestParam(name = "buId", required = false) String buId, @RequestParam(name = "yearMonth", required = false) String yearMonth){
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = WmhbUtil.getFirstDayOfMonth(new Date());
        String lastDayOfMonth = WmhbUtil.getLastDayOfMonth(new Date());
        if(!StringUtils.isEmpty(yearMonth)){
            try {
                Date date = formatter1.parse(yearMonth); // 解析字符串为Date对象
                firstDayOfMonth = WmhbUtil.getFirstDayOfMonth(date);
                lastDayOfMonth = WmhbUtil.getLastDayOfMonth(date);
            } catch (ParseException e) {
                return Result.error(e.getMessage()); // 处理异常
            }
        }
        else{
            yearMonth = formatter1.format(new Date());
        }

        List<WmInstallDebugVo> wmInstallDebugVoList = new ArrayList<>();
        List<WmProject> wmProjectList = wmProjectService.list();
        for(WmProject wmProject: wmProjectList){
            List<WmContract> wmContractList = wmContractService.queryGantContractByWmProjectId(wmProject.getId());
            for(WmContract wmContract: wmContractList) {
                List<String> wmContractIdList = new ArrayList<>();
                wmContractIdList.add(wmContract.getId());
                List<String> wmContractProductList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
                if (!wmContractProductList.isEmpty()) {
                    List<WmProductDebug> wmProductDebugList = wmTaskService.selectInstallDebugTask(wmContractProductList, firstDayOfMonth, lastDayOfMonth);
                    for (WmProductDebug wmProductDebug : wmProductDebugList) {
                        WmTask wmTask = wmTaskService.getById(wmProductDebug.getWmTaskId());
                        if (!StringUtils.isEmpty(buId) && !wmTask.getBuId().equals(buId)) {
                            continue;
                        }

                        WmInstallDebugVo wmInstallDebugVo = new WmInstallDebugVo();
                        wmInstallDebugVo.setProjectName(wmProject.getName());
                        wmInstallDebugVo.setWmContractId(wmContract.getId());
                        wmInstallDebugVo.setProductName(wmTask.getName());
                        wmInstallDebugVo.setProductCode(wmTask.getCode());
                        wmInstallDebugVo.setQuantity(wmTask.getQuantity());
                        wmInstallDebugVo.setSpecification(wmTask.getSpecification());
                        wmInstallDebugVo.setInstallPrice("");
                        wmInstallDebugVo.setMonthFee("");
                        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
                        if(wmTaskbook != null && !StringUtils.isEmpty(wmTaskbook.getWmVendorId())) {
                            WmVendor wmVendor = wmVendorService.getById(wmTaskbook.getWmVendorId());
                            if(wmVendor != null) {
                                wmInstallDebugVo.setVendorName(wmVendor.getCnName());
                            }
                        }
                        wmInstallDebugVo.setSingleWeight("");
                        wmInstallDebugVo.setTotalInstallFee("");
                        wmInstallDebugVo.setTotalFee("");
                        if(!StringUtils.isEmpty(wmProductDebug.getProgress())) {
                            wmInstallDebugVo.setTotalProgress(wmProductDebug.getProgress() + "%");
                        }
                        else{
                            wmInstallDebugVo.setTotalProgress("0%");
                        }
                        wmInstallDebugVo.setTotalWeight("");
                        if(!StringUtils.isEmpty(wmTask.getUnitOfMeasure())) {
                            String dictText = sysDictService.queryDictTextByKey(UserConstant.UNIT_OF_MESSURE, wmTask.getUnitOfMeasure());
                            wmInstallDebugVo.setUnitOfMeasure(dictText);
                        }
                        wmInstallDebugVoList.add(wmInstallDebugVo);
                    }
                }
            }
        }

        return Result.OK(wmInstallDebugVoList);
    }

    /**
     * 搜索项目合同或任务
     *
     * @param searchName
     * @return
     */
    //@AutoLog(value = "项目表-搜索项目合同或任务")
    @ApiOperation(value = "项目表-搜索项目合同或任务", notes = "项目表-搜索项目合同或任务")
    @GetMapping(value = "/searchInfo")
    public Result<List<WmSearchVo>> searchInfo(@RequestParam(name = "searchName", required = true) String searchName) {
        List<WmSearchVo> wmSearchVoList = new ArrayList<>();
        List<WmProject> wmProjectList = wmProjectService.searchByName(searchName);
        for(WmProject wmProject: wmProjectList){
            WmSearchVo wmSearchVo = new WmSearchVo();
            wmSearchVo.setName(wmProject.getName());
            wmSearchVo.setPrimaryKey(wmProject.getId());
            wmSearchVo.setType("project");
            wmSearchVo.setPlanEndTime(wmProject.getPlanEndTime());
            wmSearchVo.setPlanBeginTime(wmProject.getPlanBeginTime());
            wmSearchVoList.add(wmSearchVo);
        }
        List<WmContract> wmContractList = wmContractService.searchByName(searchName);
        for(WmContract wmContract: wmContractList){
            WmSearchVo wmSearchVo = new WmSearchVo();
            wmSearchVo.setName(wmContract.getName());
            wmSearchVo.setPrimaryKey(wmContract.getId());
            wmSearchVo.setType("contract");
            wmSearchVo.setPlanEndTime(wmContract.getPlanEndTime());
            wmSearchVo.setPlanBeginTime(wmContract.getPlanBeginTime());
            wmSearchVoList.add(wmSearchVo);
        }
        List<WmTaskbook> wmTaskbookList = wmTaskbookService.searchByName(searchName);
        for(WmTaskbook wmTaskbook: wmTaskbookList){
            WmSearchVo wmSearchVo = new WmSearchVo();
            wmSearchVo.setName(wmTaskbook.getName());
            wmSearchVo.setPrimaryKey(wmTaskbook.getId());
            wmSearchVo.setType("taskbook");
            wmSearchVo.setPlanEndTime(wmTaskbook.getPlanEndTime());
            wmSearchVo.setPlanBeginTime(wmTaskbook.getPlanBeginTime());
            wmSearchVoList.add(wmSearchVo);
        }
        List<WmTask> wmTaskList = wmTaskService.searchByName(searchName);
        for(WmTask wmTask: wmTaskList){
            WmSearchVo wmSearchVo = new WmSearchVo();
            wmSearchVo.setName(wmTask.getName());
            wmSearchVo.setPrimaryKey(wmTask.getId());
            wmSearchVo.setType("task");
            wmSearchVo.setPlanEndTime(wmTask.getPlanEndTime());
            wmSearchVo.setPlanBeginTime(wmTask.getPlanBeginTime());
            wmSearchVoList.add(wmSearchVo);
        }
        return Result.ok(wmSearchVoList);
    }

    /**
     * 搜索项目或合同
     *
     * @param projectName
     * @param contractName
     * @return
     */
    //@AutoLog(value = "项目表-搜索项目或合同")
    @ApiOperation(value = "项目表-搜索项目或合同", notes = "项目表-搜索项目或合同")
    @GetMapping(value = "/proTree")
    public Result<List<WmProject>> proTree(HttpServletRequest request, @RequestParam(name = "projectName", required = false) String projectName, @RequestParam(name = "contractName", required = false) String contractName){
        List<String> ipList = new ArrayList<>();
        ipList.add("127.0.0.1");
        ipList.add("10.99.100.128");
        ipList.add("172.22.22.111");
        ipList.add("10.99.99.195");
        ipList.add("10.99.100.120");
        String ip = request.getRemoteAddr();
        if(!ipList.contains(ip)){
            return Result.error("非法访问");
        }

        List<WmProject> wmProjectList = wmProjectService.searchByName(projectName);
        for(WmProject wmProject: wmProjectList){
            List<WmContract> wmContractList = wmContractService.searchByProjectAndName(wmProject.getId(), contractName);
            wmProject.setContractList(wmContractList);
        }

        return Result.OK(wmProjectList);
    }
}
